import requests
import os
import json
import time


def check_data(file_apth):
    with open(file_apth, 'r', encoding='utf8') as fp:
        data = fp.read()
        data = json.loads(data)
        length = len(data.keys())
        count = 0
        for item in data.items():
            # print(item)
            # print(length)
            if item[1].get('idNo') and item[1].get('name') and item[1].get('nation') and item[1].get('address'):
                continue
            else:
                print(item)
                count += 1
        print(f'识别总数：{length}；识别成功数：{length - count}')
        print(f'识别准确率：{round((length - count) / length, 5)}')


def main():
    url = 'http://123.132.248.70:18083/idfront/predict'
    current_dir = os.getcwd()
    result_file = os.path.join(current_dir, 'result_sfz_0.txt')
    target_path = r'D:\\Users\\Administrator\\Desktop\\compression_last_sfz'
    files = os.listdir(target_path)
    length = len(files)
    count = 0
    writes = {}
    start_time = time.time()
    for file in files:
        try:
            file_path = os.path.join(target_path, file)
            files = { 'draft' : open(file_path, 'rb')}
            res = requests.post(url=url, files=files)
            writes[file] = res.json().get('data')
            count += 1
            print(f'{file} 识别完成... 进度：{round((count/length) * 100, 2)}%')
            with open(result_file, 'w', encoding='utf8') as fp:
                fp.write(json.dumps(writes, ensure_ascii=False))
        except Exception as e:
            print('接口异常：%s' % e)
            continue
    print(f'耗时：{int(time.time() - start_time)} 秒')
    check_data(result_file)
        

def back_main():
    url = 'http://127.0.0.1:18083/idback/predict'
    current_dir = os.getcwd()
    result_file = os.path.join(current_dir, 'result_sfz_back.txt')
    writes = {}
    for file in os.listdir(r'E:\\train100back-new'):
        try:
            file_path = os.path.join(r'E:\\train100back-new', file)
            files = { 'draft' : open(file_path, 'rb')}
            res = requests.post(url=url, files=files)
            writes[file] = res.json().get('data')
            print('%s 识别完成...' % file)
            with open(result_file, 'w', encoding='utf8') as fp:
                fp.write(json.dumps(writes, ensure_ascii=False))
        except Exception as e:
            print('接口异常：%s' % e)
            continue

if __name__ == '__main__':
    main()
    # back_main()
    # check_data('result_sfz_0.txt')